package com.jdk.demo.nio.close唤醒select;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Test1 {

	// 阻塞在select或select(long)方法中的线程通过选择器的close方法被中断
	private static Selector selector;

	public static void main(String[] args) throws Exception {
		ServerSocketChannel serverSocketChannel1 = ServerSocketChannel.open();
		serverSocketChannel1.bind(new InetSocketAddress("localhost", 7777));
		serverSocketChannel1.configureBlocking(false);

		selector = Selector.open();

		SelectionKey selectionKey1 = serverSocketChannel1.register(selector, SelectionKey.OP_ACCEPT);

		Thread client = new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
					// 2s之后抛出java.nio.channels.ClosedSelectorException
					selector.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		client.start();

		boolean isRun = true;
		while(isRun) {
			System.out.println("begin " + System.currentTimeMillis());
			int keycount = selector.select();
			System.out.println(" end " + System.currentTimeMillis());
			Set<SelectionKey> keys = selector.keys();
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Iterator<SelectionKey> it = selectedKeys.iterator();
			while(it.hasNext()) {
				SelectionKey key = it.next();
				it.remove();
				if(key.isAcceptable()) {
					ServerSocketChannel channel = (ServerSocketChannel)key.channel();
					ServerSocket serverSocket = channel.socket();
					Socket socket = serverSocket.accept();
					socket.close();
				}
			}
		}
		serverSocketChannel1.close();
	}

}
